from re import U
from django.http import request
import os
from django.core.management import call_command
from django.utils.functional import empty
from rest_framework import generics,response,status,serializers
from rest_framework_simplejwt.tokens import RefreshToken # jwt  json web token api token
from .serializers import RegistrationSerializer,UserSerializer
from .models import User,Tenant,Role
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework import generics, response, status, viewsets

# Create your views here.
# modelviewset

def issue_token_for(user):
    refresh_token= RefreshToken.for_user(user)
    access_token =refresh_token.access_token
    return {
        'refresh':str(refresh_token),
        'access':str(access_token)
    }

class RegisterView(generics.GenericAPIView):

    permission_classes = ()
    serializer_class = RegistrationSerializer
    
    def post(self,request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 创建租户
        schema_name = User.get_default_schema(request.data['email'])
        tenant = Tenant.objects.create(schema_name=schema_name)

        # 创建租户角色
        default_role = os.environ['DJANGO_DEFAULT_USER_ROLE']
        if default_role == 'admin':
            user_role = Role.objects.create_admin_role(tenant)
        elif default_role == 'basic':
            user_role = Role.objects.create_basic_role(tenant)
        else:
            return response.Response('遇见未知错误',status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 初始化租户的shcmea
        # 模拟 python manage.py tenant_migrate
        call_command('tenant_migrate')

        # 创建用户
        user = User.objects.create(
            email=request.data['email'],
            password=request.data['password'],
            first_name = request.data['first_name'],
            last_name=request.data['last_name'],
            tenant=tenant,
            roles=[user_role],
        )

        # 生成用户的访问令牌
        user_token = issue_token_for(user)
        serializer = UserSerializer(user)

        return response.Response({
            'access':user_token['access'],
            'user':serializer.data
        })

class LoginView(TokenObtainPairView):

    def post(self, request, *args, **kwargs):
        email, password = request.data.get('email'), request.data.get('password')

        serializer = self.get_serializer(data={
            'username': User.get_default_username(email),
            'password': password
        })

        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            raise InvalidToken(e.args[0])

        instance = serializer.user
        user_data = UserSerializer(instance).data
        tokens = serializer.validated_data

        return response.Response({
            'tokens': tokens,
            'user': user_data
        }, status=status.HTTP_200_OK)


class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        """
        Depends on whether a specifci lookup PK is given, will
        retrieve the current user's or the corresponding user's instance.
        """
        if not self.kwargs:
            user_id = self.request.user.id
            filter_kwargs = {self.lookup_field: user_id}
        else:
            filter_kwargs = {self.lookup_field: self.kwargs[self.lookup_field]}

        queryset = self.filter_queryset(self.get_queryset())
        instance = generics.get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, instance)

        return instance

    def list(self, request, *args, **kwargs):
        user_id = self.request.user.id
        instance = User.objects.get(id=user_id)
        data = UserSerializer(instance).data
        return response.Response(data, status=status.HTTP_200_OK)
